<script>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import request from '@/utils/request.js';

export default {
  name: 'Novels',
  setup() {
    const novels = ref([]);
    const categories = ref([]);
    const total = ref(0);
    const pageSize = ref(10);
    const currentPage = ref(1);
    const hasData = ref(false);

    const getCategories = async () => {
      try {
        const response = await request.get('/category');
        if (response.code === 1) {
          categories.value = response.data.map(item => ({ id: item.id, name: item.name }));
        } else {
          console.error(response.msg || '获取类别列表失败');
        }
      } catch (error) {
        console.error('服务异常');
      }
    };

    const getNovels = async (params = {}) => {
      try {
        const response = await request.get('/novel/page', { params: { ...params, status: 2 } });
        if (response.code === 1) {
          novels.value = response.data.list.map(novel => ({ ...novel, isEditing: false }));
          total.value = response.data.totals;
          hasData.value = response.data.totals > 0;
        } else {
          console.error(response.msg || '获取小说列表失败');
        }
      } catch (error) {
        console.error('服务异常');
      }
    };

    const toggleEdit = (row) => {
      row.isEditing = !row.isEditing;
    };

    const saveEdit = async (row) => {
      try {
        const response = await request.put(`/novel`, {
          id: row.id,
          title: row.title,
          authorName: row.authorName,
          avatar: row.avatar,
          category: row.category,
          publishTime: row.publishTime,
          description: row.description
        });
        if (response.code === 1) {
          ElMessage.success('保存成功');
          row.isEditing = false;
        } else {
          ElMessage.error(response.msg || '保存失败');
        }
      } catch (error) {
        ElMessage.error('服务异常');
      }
    };

    const handleAvatarChange = async (file, row) => {
      const formData = new FormData();
      formData.append('file', file.raw);

      try {
        const uploadResponse = await request.post('/upload', formData);
        if (uploadResponse.code === 1) {
          row.avatar = uploadResponse.data;
          ElMessage.success('封面上传成功');
          saveEdit(row); // 保存更改
        } else {
          ElMessage.error(uploadResponse.msg || '封面上传失败');
        }
      } catch (error) {
        ElMessage.error('服务异常');
      }
    };

    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    };

    const handleSizeChange = (val) => {
      pageSize.value = val;
      getNovels({ pageSize: val, currentPage: currentPage.value });
    };

    const handleCurrentChange = (val) => {
      currentPage.value = val;
      getNovels({ pageSize: pageSize.value, currentPage: val });
    };

    onMounted(() => {
      getCategories();
      getNovels();
    });

    return {
      novels,
      categories,
      total,
      pageSize,
      currentPage,
      handleSizeChange,
      handleCurrentChange,
      hasData,
      toggleEdit,
      saveEdit,
      formatDate,
      handleAvatarChange
    };
  }
};
</script>

<template>
  <div class="novels-container">
    <el-table :data="novels" style="width: 100%; margin-top: 20px;" v-if="hasData">
      <el-table-column prop="title" label="标题" width="180">
        <template #default="scope">
          <span v-if="!scope.row.isEditing">{{ scope.row.title }}</span>
          <el-input v-else v-model="scope.row.title" @blur="saveEdit(scope.row)" @keyup.enter="saveEdit(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="avatar" label="封面">
        <template #default="scope">
          <img :src="scope.row.avatar" alt="封面" style="width: 50px; height: 50px;" v-if="!scope.row.isEditing">
          <el-upload
            v-else
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :on-change="(file) => handleAvatarChange(file, scope.row)"
            :before-upload="() => true"
            :auto-upload="false"
          >
            <img :src="scope.row.avatar" alt="封面" style="width: 50px; height: 50px;" v-if="scope.row.avatar">
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </template>
      </el-table-column>
      <el-table-column prop="authorName" label="作者" width="100">
        <template #default="scope">
          <span v-if="!scope.row.isEditing">{{ scope.row.authorName }}</span>
          <el-input v-else v-model="scope.row.authorName" @blur="saveEdit(scope.row)" @keyup.enter="saveEdit(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="category" label="类别" width="100">
        <template #default="scope">
          <span v-if="!scope.row.isEditing">{{ scope.row.category }}</span>
          <el-select v-else v-model="scope.row.category" @change="saveEdit(scope.row)">
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.name" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="publishTime" label="发布日期" width="150">
        <template #default="scope">
          <span v-if="!scope.row.isEditing">{{ scope.row.publishTime }}</span>
          <el-input v-else v-model="scope.row.publishTime" @blur="saveEdit(scope.row)" @keyup.enter="saveEdit(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" show-overflow-tooltip>
        <template #default="scope">
          <span v-if="!scope.row.isEditing">{{ scope.row.description }}</span>
          <el-input v-else v-model="scope.row.description" type="textarea" @blur="saveEdit(scope.row)" @keyup.enter="saveEdit(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button size="mini" type="primary" @click="toggleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="success" v-if="scope.row.isEditing" @click="saveEdit(scope.row)">保存</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-else style="text-align: center; margin-top: 20px;">
      <p>暂无相关数据</p>
    </div>
    <div class="example-pagination-block" style="margin-top: 20px;" v-if="hasData">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
  </div>
</template>

<style scoped>
.novels-container {
  padding: 20px;
}

.demo-form-inline .el-input, .demo-form-inline .el-select {
  --el-input-width: 220px;
}

.example-pagination-block + .example-pagination-block {
  margin-top: 10px;
}

.example-pagination-block .example-demonstration {
  margin-bottom: 16px;
}
</style>